package cm.mefobe.android.telecomcost.view;

import java.util.ArrayList;

import cm.mefobe.android.telecomcost.TelecomCost;
import cm.mefobe.android.telecomcost.adapter.ZoneSpinnerAdapter;
import cm.mefobe.android.telecomcost.entities.Zone;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

public class ZoneSpinner extends Spinner {

	private ArrayList<Zone> _zones;
	private Context _context;
	private SpinnerAdapter _adapter;
	private Zone _zone;

	@Override
	public void setSelection(int position) {
		Log.i("ZoneSpinner", "setting selection..." + position);
		_zone = (Zone) _adapter.getItem(position);
		super.setSelection(position);
	}

	public ArrayList<Zone> getZones() {
		return _zones;
	}

	public Zone getSelectedZone() {
		return _zone;
	}

	private void setList() throws Exception {
		if (_context != null) {
			Log.i("ZoneSpinner", "binding Zones...");
			_zones = TelecomCost.getDatabaseManager().getZones();

			_adapter = new ZoneSpinnerAdapter(_context,
					android.R.layout.select_dialog_singlechoice, _zones);
		} else {
			throw new Exception(
					"cannot set the adapter of the ZoneSpinner...the context is null");
		}
	}

	@Override
	public void setAdapter(SpinnerAdapter adapter) {
		Log.i("ZoneSpinner", "setting the adapter...");
		try {
			setList();
			super.setAdapter(_adapter);
			if (_adapter != null && _adapter.getCount() > 0) {
				setSelection(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public SpinnerAdapter getAdapter() {
		return _adapter;
	}

	public ZoneSpinner(Context context) {
		super(context);
		_context = context;
	}

	public ZoneSpinner(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		_context = context;
	}

	public ZoneSpinner(Context context, AttributeSet attrs) {
		super(context, attrs);
		_context = context;
	}

	public Zone getFirstZone() {
		_zone = (_adapter != null && _adapter.getCount() > 0) ? (Zone) _adapter
				.getItem(0) : null;
		return _zone;
	}
}
